package servlets;

import hibernatelogic.HibTransactions;
import hibernatelogic.HibUsers;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Transactions;

@WebServlet("/approve-transaction-servlet")
public class ApproveTransactionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger loggerApproveTransactionsServlet = Logger
			.getLogger(ApproveTransactionsServlet.class);

	public ApproveTransactionsServlet() {
		super();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession sess = request.getSession();

		if (((String) sess.getAttribute("UserRole")).equals("2")) {

			HibTransactions hibTransactions = new HibTransactions();
			Transactions transaction = new Transactions();

			int transaction_id = Integer.parseInt(request
					.getParameter("transaction"));
			try {
				transaction = (Transactions) hibTransactions
						.getTransactionByID(transaction_id);
			} catch (SQLException e) {
				loggerApproveTransactionsServlet
						.error("Failed to create new transaction at ApproveTransactionsServlrt",
								e);
			}
			int way = Integer.parseInt(request.getParameter("approve"));
			switch (way) {
			case 1:
				transaction.status = "A";
				try {
					hibTransactions.updateTransaction(transaction);
				} catch (SQLException e) {
					loggerApproveTransactionsServlet
							.error("Failed to update transaction at ApproveTransactionsServlet",
									e);
				} finally {
					hibTransactions = null;
					transaction = null;
					response.sendRedirect("/my-pet-project-0/MApproveTransaction.jsp");
				}
				break;
			case 0:
				try {
					hibTransactions.deleteTransactions(transaction);
				} catch (SQLException e) {
					loggerApproveTransactionsServlet
							.error("Failed to dissaprove transaction at ApproveTransactionsServlet",
									e);
				} finally {
					hibTransactions = null;
					transaction = null;
					response.sendRedirect("/my-pet-project-0/MApproveTransaction.jsp");
				}
				break;
			default:
				response.sendRedirect("/my-pet-project-0/MApproveTransaction.jsp");
				break;
			}
		} else {
			response.sendError(response.SC_FORBIDDEN);
		}
	}
}
